package org.sanmao.wyj.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.sanmao.wyj.controller.utils.R;
import org.sanmao.wyj.dao.MessageDao;
import org.sanmao.wyj.domain.Message;
import org.sanmao.wyj.exception.CreatorIsNotMeException;
import org.sanmao.wyj.service.MessageService;
import org.sanmao.wyj.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Service
public class MessageServiceImpl extends ServiceImpl<MessageDao, Message> implements MessageService {
    @Autowired
    private MessageDao messageDao;
    @Override
    public Boolean saveMsg(Message msg, HttpServletRequest request) {
        Date date = new Date(System.currentTimeMillis());
        msg.setTime(date);
        String token = request.getHeader("token");
        String creatorId = "u"+ JwtUtils.getUserId(token);
        msg.setCreatorid(creatorId);
        return messageDao.insert(msg) > 0;
    }


    @Override
    public Boolean workerSaveMsg(Message msg, HttpServletRequest request) {
        Date date = new Date(System.currentTimeMillis());
        msg.setTime(date);
        String token = request.getHeader("token");
        String creatorId = "w"+ JwtUtils.getUserId(token);
        msg.setCreatorid(creatorId);
        return messageDao.insert(msg) > 0;
    }

    @Override
    public boolean workerDelMsgById(int mid, HttpServletRequest request) {
        Message message = messageDao.selectById(mid);
        String creatorid = message.getCreatorid();
        String token = request.getHeader("token");
        int userId = JwtUtils.getUserId(token);
        try{
            if(creatorid.equals("w"+userId)){
                return messageDao.deleteById(mid) > 0;
            }
            else {
                throw new CreatorIsNotMeException("非自己留言不能删除");
            }
        }catch (RuntimeException e){
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean userDelMsgById(int mid, HttpServletRequest request) {
        Message message = messageDao.selectById(mid);
        String creatorid = message.getCreatorid();
        String token = request.getHeader("token");
        int userId = JwtUtils.getUserId(token);
        try{
            if(creatorid.equals("u"+userId)){
                return messageDao.deleteById(mid) > 0;
            }
            else {
                throw new CreatorIsNotMeException("非自己留言不能删除");
            }
        }catch (RuntimeException e){
            e.printStackTrace();
            return false;
        }
    }

}
